/**
 * AnalyzeErrorsBase.java
 *
 * Copyright (c) Viorel Tacliciu 2009. All Rights Reserved.
 *
 * This source file may not be copied, modified or redistributed,
 * in whole or in part, in any form or for any reason, without the express
 * written consent of Viorel Tacliciu. 
 **/
package ro.prjmanager.core.dao;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.hibernate.LockMode;
import org.hibernate.Criteria;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Criterion;

import java.io.Serializable;
import java.util.List;

public class GenericListDao extends HibernateDaoSupport {
    private Class persistentClass;
    

    public void setPersistentClass(Class persistentClass) {
        this.persistentClass = persistentClass;
    }

    public Object find(Serializable id, boolean lock) {
        Object entity;
        if (lock) {
            entity =  getSession().get(
                    getPersistentClass(), id, LockMode.UPGRADE);
        } else {
            entity =  getSession().get(
                    getPersistentClass(), id);
        }
        return entity;
    }

    public Class getPersistentClass() {
        return persistentClass;
    }


    public List findAll() {
        return find();
    }


    public List findByExample(Object exampleInstance) {
        return find(Example.create(exampleInstance));
    }


    public Object create(Object p_entity) {
        getSession().saveOrUpdate(p_entity);
        return p_entity;
    }

    public void delete(Object entity) {
        getSession().delete(entity);
    }


    protected List find(Criterion... p_criterion) {
        Criteria crit = getSession().createCriteria(
                getPersistentClass());
        for (Criterion c : p_criterion) {
            crit.add(c);
        }
        return crit.list();
    }


}



